<template>
  <div v-loading="loading">
    <!-- 顶部大标题 + 搜索框 -->
    <div class="cooperate-title">
      <h2>让报告搜索高效、准确、简单</h2>
      <div class="search-bar">
        <el-input
          v-model="form.keyWord"
          placeholder="请输入关键字进行搜索"
          clearable
          @clear="onSearch"
          @keyup.enter="onSearch"
        >
          <template #append>
            <el-button type="primary" @click="onSearch" class="search-btn">
              <el-icon class="search-icon"><Search /></el-icon>
              搜索
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 筛选面板 -->
    <div class="filter-panel">
      <!-- 行业分类 -->
      <div class="filter-row">
        <span class="label">行业分类：</span>
        <el-button
          v-for="cat in industryCategories"
          :key="cat.value"
          :type="form.industry_1_id === cat.value ? 'primary' : 'default'"
          size="mini"
          @click="selectIndustry(cat.value)"
        >
          {{ cat.label }}
        </el-button>
      </div>

      <!-- 二级分类 -->
      <div class="filter-row subcats" v-if="subCategories.length">
        <span class="label" style="color: #0080d1">二级分类：</span>
        <el-button
          v-for="sub in subCategories"
          :key="sub.code"
          :type="form.industry_2_id === sub.code ? 'primary' : 'default'"
          size="mini"
          @click="selectSubCategory(sub.code)"
        >
          {{ sub.label }}
        </el-button>
      </div>

      <!-- 排序 & 价格 -->
      <div class="filter-row">
        <span class="label">排序方式：</span>
        <el-button
          v-for="opt in sortOptions"
          :key="opt.value"
          :type="form.orderBy === opt.value ? 'primary' : 'default'"
          size="mini"
          @click="selectSort(opt.value)"
        >
          {{ opt.label }}
        </el-button>
      </div>
      <div class="filter-row">
        <span class="label">价格分类：</span>
        <el-button
          v-for="opt in priceOptions"
          :key="opt.value"
          :type="form.priceType === opt.value ? 'primary' : 'default'"
          size="mini"
          @click="selectPriceType(opt.value)"
        >
          {{ opt.label }}
        </el-button>
      </div>

      <!-- 当前选择 -->
      <div class="filter-row" v-if="currentSelections.length">
        <span class="label">当前选择：</span>
        <el-tag
          v-for="sel in currentSelections"
          :key="sel.key"
          closable
          @close="handleTagClose(sel.key)"
          style="margin-right: 8px"
        >
          {{ sel.label }}
        </el-tag>
      </div>
    </div>

    <!-- 产品列表 -->
    <div class="product-list">
      <template v-if="!loading && reportList.length">
        <div
          class="product-item"
          v-for="(item, index) in reportList"
          :key="index"
        >
          <div
            class="price-tag"
            :class="{ free: item.price === '免费' || item.price == 0 }"
          >
            {{ item.price == 0 ? "免费" : "￥" + item.price }}
          </div>
          <div class="img-wrapper">
            <img :src="item.coverPic" alt="" />
            <div class="img-title">{{ item.title }}</div>
          </div>
          <div class="hover-buttons"></div>
          <div class="product-item-right">
            <p class="title">{{ item.title }}</p>
            <p class="introduce">{{ item.script }}</p>
            <p class="meta">
              <span class="meta-item">
                <el-icon><User /></el-icon>
                {{ item.author }}
              </span>
              <span class="meta-item">
                <el-icon><Calendar /></el-icon>
                {{ dayjs.unix(Number(item.publishTime)).format("YYYY-MM-DD") }}
              </span>
              <span v-if="item.sizeNum" class="meta-item">
                <el-icon><Document /></el-icon>
                共{{ item.sizeNum }}页
              </span>
            </p>

            <div style="display: flex; gap: 16px">
              <button class="btn-view" @click.stop.prevent="handleView(item)">
                查看详情
              </button>
              <button
                class="btn-download"
                @click.stop.prevent="handleDownload(item)"
              >
                下载报告
              </button>
            </div>
          </div>
        </div>
      </template>

      <template v-else-if="!loading && !reportList.length">
        <el-empty description="暂无数据" style="margin: 60px auto" />
      </template>
    </div>

    <div style="margin: 0 auto; width: 500px">
      <reportPagination
        :total="Number(total)"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :page="form.pageNum"
        :limit="form.pageSize"
      >
      </reportPagination>
    </div>
  </div>
</template>

<script setup>
import reportPagination from '../components/reportPagination.vue'
import { reportApi } from '../api/report.js'
import { reactive, computed, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import dayjs from 'dayjs'
import { Search, Bottom } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
const rawIndustry = ref({})
const route = useRoute()
const router = useRouter()
const loading = ref(false)
// 搜索表单
const form = reactive({
  keyWord: '',
  industry_1_id: 'all',
  industry_2_id: '',
  orderBy: '',
  priceType: 'all',
  pageNum: 1,
  pageSize: 9
})
// 排序选项
const sortOptions = [
  { label: '热门', value: '1' },
  { label: '时间', value: '2' },
]

// 价格选项
const priceOptions = [
  { label: '全部', value: '0' },
  { label: '付费', value: '1' },
  { label: '免费', value: '2' }
]

// 行业分类
const industryCategories = ref([])

// 产品列表示例
const reportList = ref([])


const handleCurrentChange = (page) => {
  form.pageNum = page
  onSearch()
}
const handleSizeChange = (limit) => {
  form.pageSize = limit;
  form.pageNum = 1;  // 重置到第一页
  onSearch();
}


const selectIndustry = (code) => {
  form.industry_1_id = code
  form.industry_2_id = "";
  onSearch();
}
const selectSubCategory = (code) => {
  form.industry_2_id = code
  onSearch();
}
const selectSort = (value) => {
  form.orderBy = value;
  onSearch();
}

const selectPriceType = (value) => {
  form.priceType = value;
  onSearch();
}

// 当前选择
const currentSelections = computed(() => {
  const selections = [];

  // 行业分类
  if (form.industry_1_id && form.industry_1_id !== 'all') {
    const mainCat = industryCategories.value.find(c => c.value === form.industry_1_id);
    if (mainCat) {
      selections.push({
        label: mainCat.label,
        key: 'industry_1'
      });
    }
  }

  // 二级分类
  if (form.industry_2_id) {
    const subCat = subCategories.value.find(c => c.code === form.industry_2_id);
    if (subCat) {
      selections.push({
        label: subCat.label,
        key: 'industry_2'
      });
    }
  }

  // 排序方式
  const sort = sortOptions.find(o => o.value === form.orderBy);
  if (sort) {
    selections.push({
      label: `排序：${sort.label}`,
      key: 'sort'
    });
  }

  // 价格分类
  const price = priceOptions.find(o => o.value === form.priceType);
  if (price && form.priceType !== '0') { // 0 是"全部"的value
    selections.push({
      label: `价格：${price.label}`,
      key: 'price'
    });
  }

  return selections;
});

// 处理标签关闭
const handleTagClose = (key) => {
  switch (key) {
    case 'industry_1':
      form.industry_1_id = '';
      form.industry_2_id = '';
      break;
    case 'industry_2':
      form.industry_2_id = '';
      break;
    case 'sort':
      form.orderBy = ''; // 重置为默认排序
      break;
    case 'price':
      form.priceType = '0'; // 重置为"全部"
      break;
  }
  onSearch();
};






const total = ref(0)

const onSearch = async () => {
  loading.value = true
  try {
    const params = { ...form }
    const res = await reportApi.search(params)
    if (res.code === 0) {
      reportList.value = res.data.listPage.info
      total.value = res.data.listPage.num

    }
  } catch (error) {
    ElMessage.error('请求失败')
  } finally {
    loading.value = false
  }
}

// 二级分类映射
const subCategories = computed(() => {
  if (!form.industry_1_id || form.industry_1_id === "all") return [];
  const category = rawIndustry.value[form.industry_1_id];
  return category?.children ? Object.values(category.children) : [];
});

const handleView = (item) => {
  // 检查是否为免费报告
  if (item.price === '0') {
    // 解析免费报告详情页的完整URL
    const freeUrl = router.resolve({
      name: 'productDetail',
      params: { code: item.code }
    }).href;

    // 在新标签页打开免费报告
    window.open(freeUrl, '_blank');
  } else {
    // 解析付费报告详情页的完整URL
    const paidUrl = router.resolve({
      name: 'productDetailcharge',
      params: { code: item.code }
    }).href;

    // 在新标签页打开付费报告
    window.open(paidUrl, '_blank');
  }
}


const handleDownload = async (item) => {
  try {
    const res = await reportApi.reportDownload({ code: item.code })
    if (res.code === 0) {
      // 创建 a 标签触发下载
      const a = document.createElement('a')
      a.href = res.data.userDown.pdfDir
      a.download = ''
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      ElMessage.success('下载开始')
    } else {
      ElMessage.error(res.msg || '下载失败')
    }
  } catch {
    ElMessage.error('下载出错')
  } finally {

  }
}
onMounted(async () => {
  loading.value = true  // 添加loading状态
  try {
    if (route.query.keyword) {
      form.keyWord = decodeURIComponent(route.query.keyword)
    }
    const res = await reportApi.getIndustry()
    rawIndustry.value = res.data.industry || {}
    industryCategories.value = [
      { value: 'all', label: '全部' },
      ...Object.values(rawIndustry.value).map(item => ({
        value: item.code,
        label: item.label
      }))
    ]
    await onSearch()
  } finally {
    loading.value = false
  }
})
</script>               
<style scoped lang="scss">
.cooperate-title {
  background: url("../assets/xwimg/productView.png") center/cover no-repeat;
  height: 130px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  h2 {
    color: #004d7d;
    font-size: 24px;
    font-weight: 600;
    margin-bottom: 16px;
  }
  .search-bar {
    width: 50%;
    min-width: 400px;
  }
  .search-btn {
    color: #ffffff;
    background-color: #0080d1 !important;
    padding: 0 25px;
    .search-icon {
      margin-right: 8px;
      font-size: 16px;
      color: #ffffff;
    }
  }
}

.filter-panel {
  display: flex;
  flex-direction: column;
  width: 80%;
  margin: 20px auto;
  .filter-row {
    display: flex;
    flex-wrap: wrap; // 允许换行
    align-items: center;
    margin-bottom: 12px;
    gap: 8px 16px; // 行间距8px 列间距16px
    .label {
      width: 80px;
      flex-shrink: 0; // 防止标签被压缩
      margin-bottom: 3px;
      font-size: 16px;
      line-height: 100%;
      color: #333;
    }
    .el-button {
      margin: 0 !important;
      flex-shrink: 0;
    }
  }
  .subcats {
    padding-left: 80px;
    border: 1px dashed #ccc;
    border-radius: 4px;
    margin-top: -8px;
    padding-top: 8px;
    padding-bottom: 8px;
    .label {
      width: auto;
      margin-right: 16px;
      position: absolute;
      transform: translateX(-100%);
    }
  }
}

.product-list {
  min-height: 200px;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center; /* 在主轴（水平方向）上居中 */
  align-content: center; /* 多行内容在交叉轴（垂直方向）上居中 */
  gap: 30px;
  width: 100%; /* 改为 100%，方便显示三列 */
  margin: 0 auto;
  // text-align: center;
}

.product-item {
  background: linear-gradient(to right, #fff, #e5f1f9);
  display: flex;
  align-items: center;
  position: relative;
  overflow: hidden;
  margin-bottom: 20px;
  width: 28%; /* 改为 30%，原 48%，使一行三列 */
  height: 250px;
  border-radius: 12px;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.2);
  }

  &::after {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #1e6a9a3d;
    opacity: 0;
    transition: inherit;
    pointer-events: none;
  }

  .img-wrapper {
    position: relative;
    .img-title {
      position: absolute;
      top: 30%;
      left: 45%;
      /* 先把文字中心移到容器中心 */
      transform: translate(-50%, -50%) rotate(-5deg);
      /* 文字样式 */
      font-size: 11px;
      font-weight: bold;
      font-style: italic;
      color: #fff;
      text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
      white-space: nowrap;
      pointer-events: none;
      width: 120px;
      text-align: center;
      white-space: nowrap; /* 防止文本换行 */
      overflow: hidden; /* 隐藏溢出的内容 */
      text-overflow: ellipsis; /* 显示省略号来代表被修剪的文本 */
    }
  }

  .price-tag {
    position: absolute;
    top: 5px;
    right: 5px;
    padding: 4px 10px;
    background-color: #ff9c00;
    color: #fff;
    font-size: 12px;
    font-weight: 600;
    border-radius: 12px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
    z-index: 10;
    &.free {
      background-color: #209c3f;
    }
  }

  .meta {
    display: flex;
    gap: 10px;
    margin-top: 12px;
    align-items: center;
    color: #999;
    overflow: hidden; // 限制子元素超出
    text-overflow: ellipsis;
    white-space: nowrap;
    max-width: 100%;
  }

  /* 修改按钮样式部分 */
  .btn-download,
  .btn-view {
    margin-top: 30px;
    height: 35px;
    width: 110px;
    padding: 10px 25px;
    border: none;
    border-radius: 8px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    .el-icon {
      font-size: 16px;
      transition: color 0.2s ease;
    }
    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    }
  }

  .btn-download {
    background: #0080d1;
    color: white;
    &:hover {
      background: #0080d1;
    }
    .el-icon {
      color: rgba(white, 0.9);
    }
  }

  .btn-view {
    background: rgba(white, 0.95);
    color: #151618b8;
    border: 1px solid rgba(#151618b8, 0.2);
  }

  img {
    display: block;
    margin: 20px 30px;
    width: 144px;
    height: 210px;
    object-fit: cover;
  }

  .product-item-right {
    padding: 15px;
    margin-top: 35px;
    margin-bottom: 70px;
    .title {
      color: #333;
      font-weight: 600;
      font-size: 17px;

      width: 230px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .introduce {
      font-size: 12px;
      font-weight: 600;
      color: #999;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }
    .meta {
      font-size: 12px;
      color: #999;
    }
  }
}
.intro {
  flex: 0 0 46%;
  padding: 24px;
}
.intro-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 16px;
}

.intro-title .icon {
  width: 24px;
  height: 24px;
  color: #0080d1;
}

.intro-text {
  color: #666;
  line-height: 1.6;
  margin-bottom: 24px;
}

.more-btn {
  background-color: #0080d1;
  color: #fff;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

@media (max-width: 768px) {
  .filter-panel {
    width: 95%;
  }

  .cooperate-title .search-bar {
    width: 80%;
  }

  .product-list {
    width: 95%;
    gap: 15px;
  }

  .product-item {
    width: 100%;
  }
}
.el-loading-spinner .path {
  stroke: #0080d1 !important;
}
.el-loading-spinner .el-loading-text {
  color: #0080d1 !important;
}
</style>
